//
//  NPC.m
//  gong
//
//  Created by echo on 14-1-11.
//  Copyright (c) 2014年 echo. All rights reserved.
//

#import "NPC.h"
#import "UICreator.h"
#import "PositionTools.h"
#import "Constants.h"

#define NPCPositionMapInfo @{@"左一":@(ShowAtTheLeft1),@"左二":@(ShowAtTheLeft2),@"中":@(ShowInTheMiddle),@"右一":@(ShowAtTheRight1),@"右二":@(ShowAtTheRight2),@"左":@(ShowAtTheLeft),@"右":@(ShowAtTheRight)}


@implementation NPC
{
    NSDictionary *_info;
    UIImageView *_currentAvatar;
    UIImageView *_streetAvatar;
    ShowPosition _showPosition;
    
    UIImageView *_dialogBk;
    UILabel *_dialogLabel;
    
    UIButton *_visitButton;
    NSInteger _currentScriptIndex;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (id)initWithContainer:(UIView*)containerView info:(NSDictionary*)info
{
    self = [super init];
    if (self) {
        _info = info;
        self.containerView = containerView;
        self.isShowInStreet = NO;
        [self initDefault];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(leave) name:MsgLeavePlace object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNPCTalk:) name:MsgNPCTalk object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearTalk) name:MsgClearTalk object:nil];
    }

    return self;
}

- (void)initDefault
{
    
}

- (NSString*)getRandomTalk
{
    return nil;
}

- (void)show
{
    
}

- (void)createAvatar
{
    _currentAvatar = [UICreator createImageViewFromImagename:_currentNPCImageName];
    [_containerView addSubview:_currentAvatar];
    _currentAvatar.tag = CurrentAvatarTag;
    
    if (_info[@"铭牌"]) {
        UIImageView *namePlate = [UICreator createImageViewFromImagename:_info[@"铭牌"]];
        [PositionTools placeView:namePlate atTheCenterOfTheView:_currentAvatar];
        
        namePlate.center = CGPointMake(namePlate.center.x + [_info[@"铭牌偏移"][@"x"] floatValue], namePlate.center.y + [_info[@"铭牌偏移"][@"y"] floatValue]);
    }
    
    self.canSelect = NO;
    _currentAvatar.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    [_currentAvatar addGestureRecognizer:tap];
}

- (void)handleTap:(UIGestureRecognizer*)gesture
{
    if (_currentScriptIndex < _randomScriptArray.count) {
        NSString *script = _randomScriptArray[_currentScriptIndex];
        [self talk:script];
        
        _currentScriptIndex++;
        if (_currentScriptIndex > _randomScriptArray.count - 1) {
            _currentScriptIndex = 0;
        }
    }
    
    if (self.canSelect) {
        if (self.selectTargetAction) {
            self.selectTargetAction();
            self.selectTargetAction = nil;
            self.canSelect = NO;
        }
    }
}

- (CGFloat)getPositionX:(ShowPosition)showPosition
{
    if (ShowInTheMiddle == showPosition) {
        return _containerView.frame.size.width * 0.5;
    } else if (ShowAtTheLeft1 == showPosition) {
        return _containerView.frame.size.width * 0.3;
    } else if (ShowAtTheLeft2 == showPosition) {
        return _containerView.frame.size.width * 0.1;
    } else if (ShowAtTheRight1 == showPosition) {
        return _containerView.frame.size.width * 0.7;
    } else if (ShowAtTheRight2 == showPosition) {
        return _containerView.frame.size.width * 0.9;
    } else if (ShowAtTheLeft == showPosition) {
        return _containerView.frame.size.width * 0.25;
    } else if (ShowAtTheRight == showPosition) {
        return _containerView.frame.size.width * 0.75;
    } else {
        return _containerView.frame.size.width * 0.5;
    }
}

- (void)show:(ShowPosition)showPosition
{
    NSLog(@" %@ show at %i", self.name, showPosition);
 
    _showPosition = showPosition;
    
    [self createAvatar];
    
    if (ShowInTheMiddle == showPosition) {
        [PositionTools placeView:_currentAvatar atTheBottomMiddleOfTheView:_containerView offset:0];
    } else {
        _currentAvatar.center = CGPointMake([self getPositionX:showPosition], _containerView.frame.size.height - _currentAvatar.frame.size.height/2);
    }
    
    _currentAvatar.alpha = 0;
    [UIView animateWithDuration:.4 animations:^{
        _currentAvatar.alpha = 1;
    }];
    
    _currentAvatar.userInteractionEnabled = YES;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:MsgShowNPC object:nil];
}

- (void)showWithDescripter:(NSString*)positionDescriptor
{
    ShowPosition position = (ShowPosition)[NPCPositionMapInfo[positionDescriptor] integerValue];
    [self show:position];
}

- (void)createStreetAvatar
{
    _streetAvatar = [UICreator createImageViewFromImagename:_steetImageName use2X:YES];
}

- (void)showInStreet:(UIView*)streetView withPosition:(CGPoint)position
{
    self.isShowInStreet = YES;
    [streetView addSubview:_streetAvatar];
    _streetAvatar.center = position;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showNpcHouseEntry:)];
    [_streetAvatar addGestureRecognizer:tap];
    
    [self performSelector:@selector(leaveStreet) withObject:nil afterDelay:NpcShowInStreetTime];
}

- (void)showNpcHouseEntry:(UIGestureRecognizer*)gesture
{
    if (!_visitButton) {
        _visitButton = [UICreator createButtonWithNormalImage:@"door.png" highlightedImage:nil target:self action:@selector(visit) use2X:YES];
        [PositionTools placeView:_visitButton atTheCenterOfTheView:_streetAvatar];
    }
    
    [self performSelector:@selector(removeVisitButton) withObject:nil afterDelay:5];
}

- (void)removeVisitButton
{
    [_visitButton removeFromSuperview];
    _visitButton = nil;
}

- (void)visit
{
    [[NSNotificationCenter defaultCenter] postNotificationName:MsgVisitNpcHouse object:self];
}

- (void)leaveStreet
{
    self.isShowInStreet = NO;
    [[NSNotificationCenter defaultCenter] postNotificationName:MsgStreetNpcLeave object:nil];
    [_streetAvatar removeFromSuperview];
}

- (void)talk:(NSString *)text
{
    if (!_dialogBk) {
        _dialogBk = [UICreator createImageViewFromImagename:_info[@"对话框"]];
    }
    
    _dialogBk.alpha = 1;
    [PositionTools placeView:_dialogBk atTheCenterOfTheView:_currentAvatar];
    _dialogBk.center = CGPointMake(_dialogBk.center.x + [_info[@"对话框偏移"][@"x"] floatValue], _dialogBk.center.y + [_info[@"对话框偏移"][@"y"] floatValue]);
    
    if (_dialogLabel) {
        [_dialogLabel removeFromSuperview];
    }
    _dialogLabel = [UICreator createLabel:text
                            constrainedSize:CGSizeMake(_dialogBk.frame.size.width - 40, CGFLOAT_MAX)
                                      color:[UIColor blackColor]
                                       font:[UIFont systemFontOfSize:20]];
    
    if (_dialogLabel.frame.size.height > _dialogBk.frame.size.height - 20) {
        _dialogBk.frame = CGRectMake(_dialogBk.frame.origin.x, _dialogBk.frame.origin.y,
                                     _dialogBk.frame.size.width,
                                     _dialogLabel.frame.size.height + 20);
    }
    
    [PositionTools placeView:_dialogLabel atTheCenterOfTheView:_dialogBk];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:MsgNPCTalk object:self];
}

- (void)handleNPCTalk:(NSNotification*)notification
{
    id object = [notification object];
    if (![object isEqual:self]) {
        _dialogBk.alpha = 0;
    }
}

- (void)clearTalk
{
    [_dialogBk removeFromSuperview];
}

- (void)leave
{
    [_currentAvatar removeFromSuperview];
}

- (void)moveTo:(NSString*)positionDescriptor
{
    ShowPosition showLocation = (ShowPosition)[NPCPositionMapInfo[positionDescriptor] integerValue];
    [UIView animateWithDuration:.5 animations:^{
        _currentAvatar.center = CGPointMake([self getPositionX:showLocation], _currentAvatar.center.y);
    }];
}

@end
